/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package PropertyRental.ejb.beans;

import PropertyRental.ejb.persistence.Account;
import PropertyRental.ejb.persistence.Agent;
import PropertyRental.ejb.persistence.Customer;
import PropertyRental.ejb.persistence.Owner;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Bast
 */
@Stateless
public class AccountFacade extends AbstractFacade<Account> {
    @PersistenceContext(unitName = "PropertyRental-ejbPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public AccountFacade() {
        super(Account.class);
    }

    public boolean addAccount(String username, String password, int type, String givenName, String lastName, String email, double rent){
        Account acc = null;

        switch (type){
            case 1: acc = new Agent(username, password);
                break;
            case 2: acc = new Owner(username, password, givenName, lastName, email);
                break;
            case 3: acc = new Customer(username, password, givenName, lastName, email, rent);
                break;
        }
        
        try{
            create(acc);
        } catch (Exception e) {
            return false ;
        }
        return true;
    }

    public void deleteAccount(Account acc){
        acc = em.merge(acc);
        em.remove(acc);
    }

    public Account findByUsernamePassword(String username, String password){
        Query query = em.createQuery(
                "SELECT account FROM Account account" +
                " WHERE account.username = :username" +
                " AND account.password = :password ;");
            query.setParameter("username",username);
            query.setParameter("password",password);
        List resultList = query.getResultList();
        if (!resultList.isEmpty()){
            String nom = ((Account) resultList.get(0)).toString();
            System.out.println(resultList.size()+nom);
            return (Account) resultList.get(0);
        }
        else{
            List<Account> listeUtilisateurs = this.findAll();
            if(listeUtilisateurs.isEmpty()){
                Account acc = new Agent(username, password);
                this.create(acc);
                return acc;
            }else {
                return null;
            }
        }
    }

}
